import React, { useEffect, useRef, useState } from 'react';
import { Chart } from '@antv/g2';
import { productsBuyWay } from "../../../api/axios8081";

interface ProductData {
  priceType: string;
  num: number;
}

interface PieChartProps {
  beginTime?: string;
  endTime?: string;
}

interface ChartData {
  item: string;
  percent: number;
}

const PieChart: React.FC<PieChartProps> = ({ beginTime, endTime }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const [chartData, setChartData] = useState<ChartData[]>([]);

useEffect(() => {
    // 定义一个异步函数并在useEffect内部调用它  
    const fetchData = async () => {
      try {
        // 调用接口获取数据 

        const response = await productsBuyWay(beginTime, endTime);
        if (response.data) {
          console.log(response.data);
          const rawData: ProductData[] = response.data;
          const total = rawData.reduce((acc, curr) => acc + curr.num, 0);
          const processedData: ChartData[] = rawData.map((item) => ({
            item: item.priceType,
            percent: item.num / total,
          }));
          console.log(response.data);
          setChartData(processedData);
        }
      } catch (error) {
        console.error('Error fetching data for pie chart:', error);
      }
    };

    // 调用异步函数  
    fetchData();
  }, [beginTime, endTime]); // 当时间范围变化时重新获取数据 // 当时间范围变化时重新获取数据   

  useEffect(() => {
    if (chartRef.current) {
      const chart = new Chart({
        container: chartRef.current,
        autoFit: true,
        height: 400, // 可以设置具体高度，或者根据外部容器自适应  
      });

      if (chartData.length > 0) {
        chart.coordinate('theta', {
          radius: 0.75,
          innerRadius: 0.6
        });

        chart.coordinate({ type: 'theta', outerRadius: 0.8 });

        chart
          .interval()
          .data(chartData)
          .transform({ type: 'stackY' })
          .encode('y', 'percent')
          .encode('color', 'item')
          .legend('color', { position: 'bottom', layout: { justifyContent: 'center' } })
          .label({
            position: 'outside',
            text: (chartData: { item: string; percent: number }) => {
              const roundedPercent = Math.round(chartData.percent * 100);//设为整数
              return `${chartData.item}: ${roundedPercent}%`;
            }
          })
          .tooltip((data) => ({
            name: data.item,
            value: `${data.percent * 100}%`,
          }));

        chart.render();

        return () => {
          chart.destroy();
        };
      }
    }
  }, [chartData]); // 仅在chartData变化时重新渲染图表  

  return <div ref={chartRef} style={{ width: '100%', height: '400px' }} />;
};

export default PieChart;